package com.lecture.java8.cmd;

import org.apache.commons.lang3.StringUtils;

public class CmdLook {

    public CmdLook() {}

    public static CmdEntity parseToJavaCmdEntity(String cmd) {
        return parseToJavaCmdEntity(cmd,null);
    }

    public static CmdEntity parseToJavaCmdEntity(String cmd,String user) {
        CmdEntity cmdEntity = new CmdEntity();
        String osName = System.getProperty("os.name");
        String lowerOs = StringUtils.lowerCase(osName);
        if (osName.contains("Windows")) {
            cmdEntity.setSegment(new String[]{"cmd","/c",cmd});
        } else if (!lowerOs.contains("ix") && !lowerOs.contains("linux")
                && !lowerOs.contains("freebsd") && !lowerOs.contains("sunos")
                && !lowerOs.contains("solaris") && !lowerOs.contains("hp-ux")) {
            if (!lowerOs.startsWith("mac os x") && lowerOs.startsWith("darwin")) {
                return cmdEntity;
            }
        } else if (StringUtils.isBlank(user)) {
            cmdEntity.setSegment(new String[]{"/bin/sh","-c",cmd});
        } else {
            cmdEntity.setSegment(new String[]{"/bin/sh","su-" + user + "-c" + cmd});
        }
        return cmdEntity;
    }
}
